<?php

namespace app\api\exception;

use think\Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\facade\Log;
use think\Response;
use Throwable;

class ExceptionHandle extends Handle
{
    private $code;
    private $msg;
    private $statuscode;


    /**
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        $this->statuscode = $this->code = 500;

        if($e instanceof BaseException){//是否异常实例
            $this->code = $e->code;
            $this->msg = $e->message;
        }else{
            if (config('app_debug')){
                return parent::render($request, $e); // TODO: Change the autogenerated stub
            }
            $this->code = 500;
            $this->msg = $e->getMessage() ?: '很抱歉，服务器内部错误';
            Log::record($e->getMessage(),'error');
        }
        // Http异常
        if ($e instanceof HttpException)
        {
            $this->statuscode = $this->messagecode = $e->getStatusCode();
        }
        $data = [
            'msg' => $this->msg,
            'code' =>  $this->statuscode,
            'request_url' => $request->url()
        ];
        return json($data,$this->statuscode);
    }
}